<template>
  <div class="stroke-event-detail-container">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span v-if="!error">卒中事件详情</span>
          <span v-else class="error-title">卒中事件不存在</span>
          <el-button type="primary" @click="goBack">返回列表</el-button>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-loading v-model="loading" text="正在加载..." />
      </div>
      
      <div v-else-if="strokeEvent && !error" class="detail-content">
        <!-- 患者信息摘要 -->
        <div class="patient-summary-section">
          <el-card class="patient-summary-card" shadow="hover">
            <div class="patient-summary-content">
              <el-avatar :size="80" class="patient-avatar">{{ patient?.patient_name?.charAt(0) || '?' }}</el-avatar>
              <div class="patient-info">
                <h3>{{ patient?.patient_name || '未知患者' }}</h3>
                <p>ID: {{ patient?.patient_id || '-' }} | 性别: {{ patient?.gender || '-' }} | 年龄: {{ calculateAge(patient?.date_of_birth) }}岁</p>
                <p>联系电话: {{ patient?.phone_number || '-' }}</p>
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="goToPatientDetail" 
                  v-if="patient"
                >查看患者详情</el-button>
              </div>
            </div>
          </el-card>
        </div>
        
        <!-- 卒中事件基本信息 -->
        <el-descriptions class="info-section" title="事件基本信息">
          <el-descriptions-item label="事件ID">{{ strokeEvent.event_id }}</el-descriptions-item>
          <el-descriptions-item label="事件类型">{{ strokeEvent.event_type }}</el-descriptions-item>
          <el-descriptions-item label="发病时间">{{ formatDateTime(strokeEvent.onset_time) }}</el-descriptions-item>
          <el-descriptions-item label="入院时间">{{ formatDateTime(strokeEvent.admission_time) }}</el-descriptions-item>
          <el-descriptions-item label="出院时间">{{ strokeEvent.discharge_time ? formatDateTime(strokeEvent.discharge_time) : '尚未出院' }}</el-descriptions-item>
          <el-descriptions-item label="发病到入院时间间隔">{{ calculateTimeInterval(strokeEvent.onset_time, strokeEvent.admission_time) }}</el-descriptions-item>
          <el-descriptions-item label="发病部位">{{ strokeEvent.affected_location }}</el-descriptions-item>
          <el-descriptions-item label="严重程度">{{ strokeEvent.severity }}</el-descriptions-item>
          <el-descriptions-item label="是否复发">{{ strokeEvent.recurrence }}</el-descriptions-item>
          <el-descriptions-item label="临床表现" :span="4">{{ strokeEvent.clinical_manifestations }}</el-descriptions-item>
          <el-descriptions-item label="影像学检查结果" :span="4">{{ strokeEvent.imaging_results }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(strokeEvent.creation_time) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ strokeEvent.update_time ? formatDateTime(strokeEvent.update_time) : '暂无更新' }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 操作按钮 -->
        <div class="operation-section">
          <el-button type="warning" @click="editStrokeEvent">编辑事件信息</el-button>
          <el-button type="success" @click="addTreatment">添加治疗记录</el-button>
        </div>
        
        <!-- 治疗记录列表 -->
        <el-card class="treatments-card">
          <template #header>
            <div class="card-header">
              <span>治疗记录</span>
              <el-button type="primary" size="small" @click="addTreatment">新增治疗</el-button>
            </div>
          </template>
          
          <el-table 
            :data="eventTreatments" 
            style="width: 100%"
            border
          >
            <el-table-column prop="treatment_id" label="治疗ID" width="100" />
            <el-table-column prop="treatment_time" label="治疗时间" width="180" />
            <el-table-column prop="treatment_plan" label="治疗方案" width="150" />
            <el-table-column prop="thrombolytic_drug" label="溶栓药物" width="120" />
            <el-table-column prop="drug_dosage" label="药物剂量" width="100" />
            <el-table-column prop="treatment_effect" label="治疗效果" width="100" />
            <el-table-column prop="attending_physician" label="主治医生" width="120" />
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="viewTreatmentDetail(row.treatment_id)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="eventTreatments.length === 0" class="empty-state">
            <el-empty description="暂无治疗记录" />
          </div>
        </el-card>
      </div>
      
      <div v-else class="empty-state error-state">
        <div class="error-icon">
          <el-icon><CircleCloseFilled /></el-icon>
        </div>
        <h3 class="error-heading">卒中事件不存在或已被删除</h3>
        <p class="error-message">您请求的卒中事件ID可能有误，或者该事件已被删除。</p>
        <div class="error-actions">
          <el-button type="primary" @click="goBack">返回卒中事件列表</el-button>
          <el-button @click="goToHome">返回首页</el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 编辑卒中事件对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑卒中事件信息"
      width="800px"
    >
      <el-form 
        :model="editForm" 
        ref="editFormRef" 
        label-width="120px"
        :rules="formRules"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="患者ID">
              <el-input v-model="editForm.patient_id" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发病时间" prop="onset_time">
              <el-date-picker
                v-model="editForm.onset_time"
                type="datetime"
                placeholder="选择发病时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入院时间" prop="admission_time">
              <el-date-picker
                v-model="editForm.admission_time"
                type="datetime"
                placeholder="选择入院时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出院时间" prop="discharge_time">
              <el-date-picker
                v-model="editForm.discharge_time"
                type="datetime"
                placeholder="选择出院时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发病部位" prop="affected_location">
              <el-select v-model="editForm.affected_location" placeholder="请选择发病部位">
                <el-option label="前循环" value="前循环"></el-option>
                <el-option label="后循环" value="后循环"></el-option>
                <el-option label="多发" value="多发"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="严重程度" prop="severity">
              <el-select v-model="editForm.severity" placeholder="请选择严重程度">
                <el-option label="轻度" value="轻度"></el-option>
                <el-option label="中度" value="中度"></el-option>
                <el-option label="重度" value="重度"></el-option>
                <el-option label="极重度" value="极重度"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事件类型" prop="event_type">
              <el-select v-model="editForm.event_type" placeholder="请选择事件类型">
                <el-option label="缺血性卒中" value="缺血性卒中"></el-option>
                <el-option label="出血性卒中" value="出血性卒中"></el-option>
                <el-option label="短暂性脑缺血发作" value="短暂性脑缺血发作"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否复发" prop="recurrence">
              <el-select v-model="editForm.recurrence" placeholder="请选择是否复发">
                <el-option label="是" value="是"></el-option>
                <el-option label="否" value="否"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="临床表现" prop="clinical_manifestations">
              <el-input 
                v-model="editForm.clinical_manifestations" 
                placeholder="请输入临床表现"
                type="textarea"
                rows="3"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="影像学检查结果" prop="imaging_results">
              <el-input 
                v-model="editForm.imaging_results" 
                placeholder="请输入影像学检查结果"
                type="textarea"
                rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { CircleCloseFilled } from '@element-plus/icons-vue'
import { strokeEventAPI, patientAPI, treatmentAPI } from '../api'

const router = useRouter()
const route = useRoute()

// 状态数据
const loading = ref(true)
const strokeEvent = ref(null)
const patient = ref(null)
const allTreatments = ref([])
const editDialogVisible = ref(false)
const editFormRef = ref()
const error = ref(false)

// 表单验证规则
const formRules = {
  onset_time: [
    { required: true, message: '请选择发病时间', trigger: 'change' }
  ],
  admission_time: [
    { required: true, message: '请选择入院时间', trigger: 'change' }
  ],
  affected_location: [
    { required: true, message: '请选择发病部位', trigger: 'change' }
  ],
  severity: [
    { required: true, message: '请选择严重程度', trigger: 'change' }
  ],
  event_type: [
    { required: true, message: '请选择事件类型', trigger: 'change' }
  ],
  recurrence: [
    { required: true, message: '请选择是否复发', trigger: 'change' }
  ],
  clinical_manifestations: [
    { required: true, message: '请输入临床表现', trigger: 'blur' }
  ],
  imaging_results: [
    { required: true, message: '请输入影像学检查结果', trigger: 'blur' }
  ]
}

// 编辑表单
const editForm = ref({
  event_id: '',
  patient_id: '',
  onset_time: '',
  admission_time: '',
  discharge_time: '',
  affected_location: '',
  severity: '',
  event_type: '',
  recurrence: '',
  clinical_manifestations: '',
  imaging_results: ''
})

// 过滤出当前事件的治疗记录
  const eventTreatments = computed(() => {
    if (!strokeEvent.value || !allTreatments.value || !Array.isArray(allTreatments.value)) return []
    // 转换为数字进行比较，确保类型匹配
    const currentEventId = Number(strokeEvent.value.event_id)
    return allTreatments.value.filter(treatment => {
      if (!treatment || typeof treatment.event_id === 'undefined') return false
      return Number(treatment.event_id) === currentEventId
    })
  })
  
  // 处理治疗记录数据的辅助函数
  const normalizeTreatmentData = (treatments) => {
    if (!Array.isArray(treatments)) return []
    
    return treatments.map(treatment => {
      // 安全获取溶栓药物信息
      let thrombolyticDrug = '其他'
      const medicationRecord = treatment['用药记录'] || ''
      
      if (medicationRecord && typeof medicationRecord === 'string') {
        if (medicationRecord.includes('rt-PA') || medicationRecord.includes('阿替普酶')) {
          thrombolyticDrug = 'rt-PA'
        } else if (medicationRecord.includes('肝素')) {
          thrombolyticDrug = '肝素'
        } else if (medicationRecord.includes('甘露醇')) {
          thrombolyticDrug = '甘露醇'
        }
      } else if (treatment.thrombolytic_drug) {
        thrombolyticDrug = treatment.thrombolytic_drug
      } else if (treatment['溶栓药物']) {
        thrombolyticDrug = treatment['溶栓药物']
      }
      
      return {
        treatment_id: treatment['记录ID'] || treatment.id || treatment.treatment_id || '',
        event_id: treatment['卒中事件ID'] || treatment.event_id || treatment['事件ID'] || '',
        treatment_time: treatment['治疗时间'] || treatment.treatment_time || '',
        treatment_plan: treatment['治疗方式'] || treatment.treatment_plan || treatment['治疗方案'] || '',
        thrombolytic_drug: thrombolyticDrug,
        drug_dosage: treatment['用药记录'] || treatment.drug_dosage || treatment['药物剂量'] || '',
        treatment_effect: treatment['治疗效果'] || '待评估',
        attending_physician: treatment['主治医生'] || ''
      }
    })
  }

// 获取卒中事件详情
const getStrokeEventDetail = async () => {
  const eventId = route.params.id
  if (!eventId) {
    loading.value = false
    error.value = true
    return
  }
  
  loading.value = true
  try {
    // 先获取所有卒中事件，然后筛选出特定ID的事件
    const events = await strokeEventAPI.getEvents()
    const eventDetail = events.find(e => e.event_id === parseInt(eventId))
    
    if (!eventDetail) {
      error.value = true
      ElMessage.warning('卒中事件不存在')
      return
    }
    
    strokeEvent.value = eventDetail
    
    // 获取患者信息
    const patients = await patientAPI.getPatients()
    patient.value = patients.find(p => p.patient_id === strokeEvent.value.patient_id)
    
    // 获取所有治疗记录
    const treatments = await treatmentAPI.getRecords()
    // 规范化治疗记录的字段名，特别注意"卒中事件ID"字段
    allTreatments.value = treatments.map(treatment => ({
      treatment_id: treatment['记录ID'] || treatment.id || treatment.treatment_id,
      event_id: treatment['卒中事件ID'] || treatment.event_id || treatment['事件ID'],
      treatment_time: treatment['治疗时间'] || treatment.treatment_time,
      treatment_plan: treatment['治疗方式'] || treatment.treatment_plan || treatment['治疗方案'],
      thrombolytic_drug: treatment['用药记录'] ? 
        (treatment['用药记录'].includes('rt-PA') ? 'rt-PA' : 
        (treatment['用药记录'].includes('肝素') ? '肝素' : 
        (treatment['用药记录'].includes('甘露醇') ? '甘露醇' : '其他'))) : 
        treatment.thrombolytic_drug || treatment['溶栓药物'],
      drug_dosage: treatment['用药记录'] || treatment.drug_dosage || treatment['药物剂量'],
      treatment_effect: '待评估', // 根据实际数据结构可以调整
      attending_physician: treatment['主治医生'] || ''
    }))
    console.log('处理后的治疗记录数据:', allTreatments.value)
  } catch (err) {
    error.value = true
    ElMessage.error('获取卒中事件详情失败')
    console.error('获取卒中事件详情失败:', err)
  } finally {
    loading.value = false
  }
}

// 返回卒中事件列表
const goBack = () => {
  router.push('/stroke-events')
}

// 返回首页
const goToHome = () => {
  router.push('/')
}

// 查看患者详情
const goToPatientDetail = () => {
  router.push(`/patients/${patient.value.patient_id}`)
}

// 编辑卒中事件
const editStrokeEvent = () => {
  // 填充编辑表单
  editForm.value = {
    event_id: strokeEvent.value.event_id,
    patient_id: strokeEvent.value.patient_id,
    onset_time: strokeEvent.value.onset_time,
    admission_time: strokeEvent.value.admission_time,
    discharge_time: strokeEvent.value.discharge_time || '',
    affected_location: strokeEvent.value.affected_location,
    severity: strokeEvent.value.severity,
    event_type: strokeEvent.value.event_type,
    recurrence: strokeEvent.value.recurrence,
    clinical_manifestations: strokeEvent.value.clinical_manifestations,
    imaging_results: strokeEvent.value.imaging_results
  }
  editDialogVisible.value = true
}

// 提交编辑表单
const submitEditForm = async () => {
  try {
    await editFormRef.value.validate()
    
    const updatedEvent = {
      ...editForm.value,
      update_time: new Date().toISOString()
    }
    
    await strokeEventAPI.updateEvent(updatedEvent)
    ElMessage.success('卒中事件信息更新成功')
    
    // 重新获取最新数据
    await getStrokeEventDetail()
    editDialogVisible.value = false
  } catch (error) {
    if (error !== false) { // 非表单验证错误
      ElMessage.error('更新失败，请重试')
      console.error('更新失败:', error)
    }
  }
}

// 添加治疗记录
const addTreatment = () => {
  // 这里可以实现跳转到添加治疗记录页面
  ElMessage.success('添加治疗记录功能待实现')
}

// 查看治疗记录详情
const viewTreatmentDetail = (treatmentId) => {
  // 这里可以实现跳转到治疗记录详情页面
  ElMessage.success('查看治疗记录详情功能待实现')
}

// 工具方法
const formatDateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

const calculateAge = (birthDateString) => {
  if (!birthDateString) return 0
  const birthDate = new Date(birthDateString)
  const today = new Date()
  let age = today.getFullYear() - birthDate.getFullYear()
  const monthDiff = today.getMonth() - birthDate.getMonth()
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--
  }
  
  return age
}

const calculateTimeInterval = (startTime, endTime) => {
  if (!startTime || !endTime) return '-'  
  const start = new Date(startTime)
  const end = new Date(endTime)
  const diffMs = end - start
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
  const diffMinutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60))
  
  return `${diffHours}小时${diffMinutes}分钟`
}

// 组件挂载时获取卒中事件详情
onMounted(() => {
  getStrokeEventDetail()
})
</script>

<style scoped>
.stroke-event-detail-container {
  padding: 20px;
}

.page-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #000000;
}

/* 确保标题文字为黑色 */
.card-header span {
  color: #000000 !important;
}

.loading-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.detail-content {
  width: 100%;
}

/* 患者摘要卡片 */
.patient-summary-section {
  margin-bottom: 20px;
}

.patient-summary-card {
  border-left: 4px solid #409eff;
}

.patient-summary-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.patient-avatar {
  background-color: #409eff;
  font-size: 30px;
}

.patient-info h3 {
  margin: 0 0 5px 0;
  font-size: 1.2rem;
}

.patient-info p {
  margin: 5px 0;
  color: #606266;
}

/* 信息部分 */
.info-section {
  margin-bottom: 20px;
}

.operation-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  gap: 10px;
}

.treatments-card {
  margin-top: 20px;
}

.empty-state {
  padding: 40px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.error-state {
  padding: 60px 0;
  text-align: center;
}

.error-icon {
  font-size: 60px;
  color: #f56c6c;
  margin-bottom: 20px;
}

.error-title {
  color: #f56c6c;
  font-weight: bold;
}

.error-heading {
  margin: 10px 0;
  color: #303133;
  font-size: 18px;
}

.error-message {
  color: #606266;
  margin-bottom: 30px;
}

.error-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .patient-summary-content {
    flex-direction: column;
    text-align: center;
  }
  
  .patient-info {
    width: 100%;
  }
  
  .operation-section {
    flex-direction: column;
  }
}
</style>